package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.MarketAdminUserService;
import com.cskaoyan.market.service.impl.MarketAdminUserServiceImpl;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/admin/user/*")
public class AdminUserController extends HttpServlet {
    // 持有service
    MarketAdminUserService userService = new MarketAdminUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 分发请求
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/user/", "");

        System.out.println("op = " + op);

        if ("list".equals(op)) {
            list(req, resp);
        } else if ("detail".equals(op)) {
            detail(req, resp);
        }
    }

    /**
     * 按id查询单个用户
     *
     * @param req
     * @param resp
     */
    private void detail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 解析请求
        String idStr = req.getParameter("id");

        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resp.getWriter().println(
                    JacksonUtil.writeValueAsString(
                            ResponseUtil.badArgumentValue()
                    )
            );
            return;
        }


        // 调用service层获取查询结果
        MarketUser marketUser = userService.list(id);

        // 校验查询结果是否为空

        // 使用ResponseUtil封装完整的HashMap,并用Object接收
        Object ok = ResponseUtil.ok(marketUser);

        // 利用JacksonUtil将ok写为Json格式的字符串
        String s = JacksonUtil.writeValueAsString(ok);

        // 利用resp写回请求
        resp.getWriter().println(s);
    }

    /**
     * 分页查询
     * 按手机号(精确)或用户名(模糊)，组合查询单个用户
     *
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String mobile = req.getParameter("mobile");

        // System.out.println("获取不存在的parameter不会报错");

        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");

        List<MarketUser> marketUserList;

        marketUserList = userService.getUserPage(username, mobile, page, limit, sort, order);

        // 使用工具类生成完整Json结构字符串并输出
        Object okList = ResponseUtil.okList(marketUserList);
        String s = JacksonUtil.writeValueAsString(okList);

        resp.getWriter().println(s);
    }


    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/user/", "");
        if ("update".equals(op)) {
            update(req, resp);
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /**
         * 获取请求体(使用io将请求体读入内存)
         */
        String requestBody = HttpUtil.getRequestBody(req);

        // 根据Json字符串生成对象
        // 注：不要new ObjectMapper()，正确做法是利用JacksonUtil的get方法获取。不然date数据类型无法处理
        ObjectMapper mapper = JacksonUtil.getObjectMapper();
        MarketUser marketUser = mapper.readValue(requestBody, MarketUser.class);

        // 更新updateTime
        LocalDateTime now = LocalDateTime.now();
        marketUser.setUpdateTime(now);

        System.out.println(marketUser);

        // 调用service，获取返回结果
        int line = userService.updateMarkedUser(marketUser);

        System.out.println("line = " + line);

        // 校验是否更新成功
        Object o;
        if (line == 1) {
            // 响应体
            o = ResponseUtil.ok("1");

        } else {
            o = ResponseUtil.fail(505,"数据库更新失败");
        }

        String s = JacksonUtil.writeValueAsString(o);

        // resp写回响应体
        resp.getWriter().println(s);
    }
}
